// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using Antlr4.Runtime;
using Templating.Grammar.Antlr;
using static Templating.Grammar.Antlr.TemplatingParser;

namespace SnapObjects.Data
{
    internal class DataTemplateEngine : IDataTemplateEngine
    {
        public string Build(
            IDataTemplate template,
            ITemplateExportProvider provider)
        {
            var syntax = this.GetSyntax(template.Content);

            var context = new DataTemplateParserContext();

            var dataFromat = TemplateDataFormaterFactory.GetFormater(template.DataFormat);

            var visitor = new DataTemplateParser(context, provider, dataFromat);

            var result = visitor.Visit(syntax);

            return result.ToString();
        }

        public string Convert(IDataTemplate template)
        {
            var syntax = this.GetSyntax(template.Content);

            var format = TemplateDataFormaterFactory.GetFormater(template.DataFormat);
            
            var visitor = new DataTemplateConverter(format);

            var result = visitor.Visit(syntax);

            return result.ToString();
        }

        private PortalContext GetSyntax(string template)
        {
            var stream = CharStreams.fromString(template);
            var lexer = new TemplatingLexer(stream);
            var tokens = new CommonTokenStream(lexer);

            var parser = new TemplatingParser(tokens);
            var tree = parser.portal();

            return tree;
        }
    }
}
